package com.paypalpay.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.paypalpay.config.WxPayConstants;
import com.paypalpay.util.wx.*;
import com.paypalpay.util.wx.entity.AccessToken;
import com.paypalpay.util.wx.entity.WYSQAccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class WeiXinController {
    @Autowired
    private HttpSession session;

    @RequestMapping("wx")
    public void wxMsg(HttpServletRequest request, HttpServletResponse response) {

        if (request.getMethod().equalsIgnoreCase("post")) {

            try {
                Map<String, String> map = MessageUtil.xmlToMap(request);
                String msgType = map.get("MsgType");
                String toUserName = map.get("ToUserName");
                String fromUserName = map.get("FromUserName");
                String content = map.get("Content");
                // 返回的消息
                String responseMsg = "";
                // 文本消息
                if (MessageUtil.MSG_TEXT.equalsIgnoreCase(msgType)) {

                    if ("1".equalsIgnoreCase(content)) {
                        responseMsg = MessageUtil.initTextMessage(fromUserName,toUserName, MessageUtil.keChengJieShao());
                    } else if ("2".equalsIgnoreCase(content)) {
                        responseMsg = MessageUtil.initTextMessage(fromUserName,toUserName, MessageUtil.chanPinJieShao());
                    } else if ("3".equalsIgnoreCase(content)) {
                        responseMsg = MessageUtil.initNewsMessage(fromUserName,toUserName);
                    } else if ("?".equalsIgnoreCase(content)|| "？".equalsIgnoreCase(content)) {
                        responseMsg = MessageUtil.initTextMessage(fromUserName,toUserName, MessageUtil.menuText());
                    } else if ("印尼配置".equalsIgnoreCase(content)) {
                        responseMsg = MessageUtil.initTextMessage(fromUserName,toUserName, MessageUtil.yinniText());
                    } else if ("免税店".equalsIgnoreCase(content)) {
                        responseMsg = MessageUtil.initTextMessage(fromUserName,toUserName, MessageUtil.mianshuiText());
                    }
//					else {
//						responseMsg = MessageUtil.initTextMessage(fromUserName,toUserName, MessageUtil.menuText());
//					}
                } else
                    // 事件推送
                    if (MessageUtil.MSG_EVENT.equalsIgnoreCase(msgType)) {
                        String eventType = map.get("Event");
                        // CLICK事件
                        if (MessageUtil.MSG_EVENT_CLICK.equalsIgnoreCase(eventType)) {
                            responseMsg = MessageUtil.initTextMessage(fromUserName,toUserName, MessageUtil.clickHuifu());
                        // VIEW事件
                        } else if (MessageUtil.MSG_EVENT_VIEW.equalsIgnoreCase(eventType)) {
                            String url = map.get("EventKey");
                            responseMsg = MessageUtil.initTextMessage(fromUserName,toUserName, url);
                         // 关注事件推送
                        } else if (MessageUtil.MSG_EVENT_SUBSCIBE.equalsIgnoreCase(eventType)) {
                            String url = map.get("EventKey");
                            responseMsg = MessageUtil.initSubscibeMessage(fromUserName, toUserName);
                         // 扫码推送事件
                        } else if (MessageUtil.MSG_EVENT_SCANCODE_PUSH.equalsIgnoreCase(eventType)) {
                            String key = map.get("EventKey");
                            responseMsg = MessageUtil.initTextMessage(fromUserName,toUserName, key);
                        }
                    } else if (MessageUtil.MSG_LOCATION.equalsIgnoreCase(msgType)) {
                        String label = map.get("Label");
                        responseMsg = MessageUtil.initTextMessage(fromUserName,toUserName, label);
                    }
                CommonResponse.response(responseMsg, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (request.getMethod().equalsIgnoreCase("get")) {

            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            System.out.println(signature + "," + timestamp + "," + nonce + ","+ echostr);

            if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
                // 如果校验成功，返回随机字符串
                try {
                    CommonResponse.response(echostr, response);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


    }
        // 全局access_token

        @RequestMapping(value = "getAccessToken")
        public void getAccessToken (HttpServletRequest request, HttpServletResponse response){
            AccessToken token = AccessTokenUtil.getAccessToken();
            System.out.println("token:" + token.getAccess_token());
            System.out.println("expire_in:" + token.getExpires_in());
        }

        // 获取网页授权的access_token

        @RequestMapping("getAccess_token")
        public void getAccess_token (HttpServletRequest request, HttpServletResponse response){
            WYSQAccessToken accesstoken = AccessTokenUtil.getAccess_token();
            System.out.println("access_token:" + accesstoken.getAccess_token());
            System.out.println("openid:" + accesstoken.getOpenid());
            // 将openid放到request域里面去
            request.setAttribute("openid", accesstoken.getOpenid());
        }


        @RequestMapping(value = "createMenu")
        public void createMenu (HttpServletRequest request, HttpServletResponse response){
            WXMenuUtil.createMenu(AccessTokenUtil.getAccessToken().getAccess_token(), WXMenuUtil.initMenu());
        }

        // 2，点击“荔枝商城”先来一个重定向 // 地址还需要更正

        @RequestMapping(value = "/redirect", method = RequestMethod.GET)
        public String weixinRedirect (HttpServletRequest request, HttpServletResponse response){
            return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc666003e317ff9e4&" +
                    "redirect_uri=https://wx.linksfield.net/paypalpay/oauth&" +
                    "response_type=code&scope=snsapi_base&state=STATE&connect_redirect=345#wechat_redirect";
        }

        // 3，正式跳转到指定的页面

        @RequestMapping(value = "/oauth", method = RequestMethod.GET)
        public String weixinOAuth (HttpServletRequest request){
            // 得到code
            String CODE = request.getParameter("code");

            String APPID = WxPayConstants.APPID;
            String SECRET = WxPayConstants.APP_SECRET;

            // 换取access_token 其中包含了openid
            String URL = ("https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&" +
                    "grant_type=authorization_code").replace("APPID", APPID).replace("SECRET", SECRET).replace("CODE", CODE);
            try {
                // URLConnectionHelper是一个模拟发送http请求的类
                String result = HttpClientTool.httpGet(URL, null);

                JSONObject jObj = JSONObject.parseObject(result);
                String openId = jObj.get("openid").toString();
                System.out.println("取到openid了吗：" + openId);
                // 将openId放到session域里面
                session.setAttribute("openId", openId);
                System.out.println("从session取出的openId是：" + session.getAttribute("openId"));
                System.out.println("此时seesionId是：" + session.getId());
                return "redirect:https://wx.linksfield.net?openId="+openId;
                //return "redirect:https://wx.linksfield.net/dist?openId="+openId;

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
            return null;

        }
    }
